// pages/zuoti/zuoti.js
let app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
let wcache = require("../../utils/wcache.js");
let utils = require('../../utils/util.js');

var total_micro_second = 0;
var timetout = null; //用于记时期
var timeCound = null; //用于倒计时。模拟器做题的时候使用
var isStop = false;

function countdown(that) {
  that.setData({
    clock: dateformat(total_micro_second)
  });

  timetout = setTimeout(function () {
    if (!isStop) {
      total_micro_second += 1000;
      countdown(that);
    }
  }
    , 1000)
}


function countdownMoni(that) {
  that.setData({
    clock: dateformat(total_micro_second)
  });

  timeCound = setTimeout(function () {
    total_micro_second -= 1000;
    countdownMoni(that);
    if (total_micro_second <= 0) {
      clearInterval(timeCound)
      that.submitjisojuan()
    }
  }
    , 1000)
}

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  if (day < 1) {
    if (hr < 1) {
      return +min + ":" + sec + "";
    } else if (hr >= 1) {
      return hr + ":" + min + ":" + sec + "";
    }
  } else {
    return day + "天" + hr + ":" + min + ":" + sec + "";
  }
  return day + "天" + hr + ":" + min + ":" + sec + "";
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    clientHeight: 1000,
    testInfo: null,
    currentTab: 0,
    questions: null, //新数据
    letter: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
    currentQuestion: null,
    scrollTop: 0,
    modeType: 1,  //1.顺序模式2.浏览模式3.组卷模式4.错题模式5.全部解析6.模拟考场 7.错题巩固,收藏题目,8笔记
    clock: "",
    questionAnswer:"",
    buttonClicked: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.lockJixie = false;
    let test = wcache.get("ti", null);
    this.setData({
      modeType: options.type,
      questions: test.questions,
      testInfo: test
    })
    let that = this;
    wx.setNavigationBarTitle({
      title: test.name,
    })
    //计算中间内容的高度

    wx.getSystemInfo({
      success: function (res) {
        var duoyuH = 35 + 61 + 45
        if (that.data.modeType == 6) {
          duoyuH += 35
        }
        if (that.data.modeType == 8) {
          duoyuH -= 61
        }
        that.setData({
          clientHeight: res.windowHeight - duoyuH
        });
      }
    });

    if (this.data.modeType == 1 || this.data.modeType == 8) {
      this.data.currentTab = this.getCurrentPostion()
    } else if (this.data.modeType == 3) {
      total_micro_second = 0
      countdown(this)
    } else if (this.data.modeType == 6) {
      total_micro_second = test.totalTime * 60 * 1000
      countdownMoni(this)
    }

    this.loadQuestionsHtml(this.data.currentTab);
    //点击答题卡时候使用
    app.event.on("toindex", this, data => {
      this.setData({
        currentTab: data
      })
      this.loadQuestionsHtml(this.data.currentTab);
    })

    app.event.on("editext", this, (data) => {
      this.marknote(data);
    })

    //还原首页部分不让他进入在做一次页面
    app.event.emit("tryagain",-1)
  },

  /**
  * 生命周期函数--监听页面隐藏
  */
  onHide: function () {
    this.saveTi();
  },

  saveTi() {
    this.data.testInfo.questions = this.data.questions;
    wcache.put("ti", this.data.testInfo);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

    this.setData({
      replyTemArray: [],
      reply0: null,
      reply1: null,
      reply2: null,
      reply3: null,
      reply4: null,
      reply5: null,
      reply6: null,
      reply7: null,
      currentTitle: null,
      answerAnalysis: null,
      questionAnswer: null,
      currentQuestion :null,
      wxParseImgLoad:null,
      wxParseImgTap:null
    })

    if (timetout != null) { clearInterval(timetout) }
    if (timeCound != null) { clearInterval(timeCound) }
    app.event.remove("toindex", this);
    app.event.remove("editext",this);
    this.submitError();
    //如果是浏览模式的话不需要提交数据
    if (this.data.modeType == 2 || this.data.modeType == 4 || this.data.modeType == 5 || this.data.modeType == 6 || this.data.modeType == 7 || this.data.modeType == 8) { return }
    this.jiaojuan();
  },

  /**
  * 解析答案和html数据
  */
  loadQuestionsHtml(i) {
    console.log(this);
    this.setData({
      replyTemArray:[],
      reply0:null,
      reply1:null,
      reply2:null,
      reply3:null,
      reply4:null,
      reply5:null,
      reply6:null,
      reply7:null,
      currentTitle:null,
      answerAnalysis:null,
      questionAnswer:null,
      currentQuestion: null
    })

    let question = this.data.questions[i];
    //表示为直接可以查看解析和答案
    if (this.data.modeType == 2 || this.data.modeType == 8) {
      question.myAnswer = "";
      question.isFinsh = true;
    } else if (this.data.modeType == 4 || this.data.modeType == 5) {
      question.myAnswer = question.myAnswer == undefined ? '' : question.myAnswer;
      question.isFinsh = true;
    } else if (this.data.modeType == 6 || this.data.modeType == 3) {
      //模拟考试的情况不能查看解析的
      question.isFinsh = false;
    } else {
      question.isFinsh = false;
      if (question.myAnswer != undefined) {
        question.isFinsh = true;
        this.data.questions[this.data.currentTab] = question;
      }
    }

    if (question.type == '单选题') {
      this.dxdxJiexuDanan(question);
      this.isPanduanDanxuan(question);
    } else if (question.type == '多选题' || question.type == '不定项选择题') {
      this.dxdxJiexuDanan(question);
      this.isPanduanDuoxuan(question);
    } else if (question.type == '判断题') {
      this.isPanduanTi(question);
    }

    //if (!this.lockJixie){
      WxParse.wxParse('currentTitle', 'html', question.title, this)
      WxParse.wxParse('answerAnalysis', 'html', question.answerAnalysis, this)
      WxParse.wxParse('questionAnswer', 'html', question.answer, this)
    //}
    this.lockJixie = false;

    this.setData({
      currentTab: this.data.currentTab,
      questions: this.data.questions,
      currentQuestion: question,
      scrollTop: 0
    })
  },

  /**
   *  解析单选和多选的答案
   */
  dxdxJiexuDanan(question) {
    let answerList = [];
    if (question.regExAnswer == undefined) {
      let text = question.content.replace("</?(?!img|br|h\\\\d)[^>]+>", "").replace("\r\n", "");
      let regEx = text.split(/[A-Z][\\.．、:：]/)
      regEx.splice(0, 1);
      answerList = question.regExAnswer = regEx;
    } else {
      answerList = question.regExAnswer;
    }
    //解析选项
    if (answerList.length > 0) {
      for (let j = 0; j < answerList.length; j++) {
        WxParse.wxParse('reply' + j, 'html', answerList[j], this);
        if (j === answerList.length - 1) {
          WxParse.wxParseTemArray("replyTemArray", 'reply', answerList.length, this)
        }
      } 
    } else {
      WxParse.wxParseTemArray("replyTemArray", 'reply', 0, this)
    }
  }


  /**
   * 上一题
   */
  , previous() {
    this.reloadFinsh();
    this.data.currentTab -= 1;
    if (this.data.currentTab <= 0) {
      this.data.currentTab = 0;
    }
    this.loadQuestionsHtml(this.data.currentTab);
  },

  reloadFinsh() {
    let question = this.data.questions[this.data.currentTab];
    question.isFinsh = false;
    if (question.myAnswer != undefined) {
      question.isFinsh = true;
      this.data.questions[this.data.currentTab] = question;
    }
    //用于错题的时候使用
    this.submitError();
  },

  /**
   * 下一题
   */
  next() {
    console.log(this);
    utils.buttonClicked(this);
    this.reloadFinsh();
    this.data.currentTab += 1;
    if (this.data.currentTab >= this.data.questions.length - 1) {
      this.data.currentTab = this.data.questions.length - 1;
    }
    this.loadQuestionsHtml(this.data.currentTab);
  }

  /**
   * 监听输入
   */
  , userInput(e) {
    let daan = e.detail.value;
    let question = this.data.questions[this.data.currentTab];
    question.myAnswer = daan;
    this.data.questions[this.data.currentTab] = question;
  }

  /**
   * 判断当前题单选的类型
   * normal没有作答,select正确,error错误
   */
  , isPanduanDanxuan(question) {
    let answerList = question.regExAnswer;
    let danxuanDaAn = [];
    if (this.data.modeType == 6 || this.data.modeType == 3) {
      question.isFinsh = false;
      for (let j = 0; j < answerList.length; j++) {
        if (question.myAnswer == undefined) {
          danxuanDaAn.push('normal');
        } else {
          if (question.myAnswer == this.data.letter[j]) {
            danxuanDaAn.push('select');
          } else {
            danxuanDaAn.push('normal');
          }
        }
      }
    } else {
      for (let j = 0; j < answerList.length; j++) {
        if (question.myAnswer == undefined) {
          danxuanDaAn.push('normal');
        } else {
          if (question.answer == this.data.letter[j]) {
            danxuanDaAn.push('select');
          } else {
            if (question.myAnswer == this.data.letter[j]) {
              danxuanDaAn.push('error');
            } else {
              danxuanDaAn.push('normal');
            }
          }
        }
      }
    }
    question.isPanduanDanxuan = danxuanDaAn;
    this.data.questions[this.data.currentTab] = question;
    //需要记录刷新
    this.setData({
      questions: this.data.questions,
      currentQuestion:question
    })
  },


  /**
     * 判断当前多题单选的类型
     * normal没有作答,select正确,error错误
     */
  isPanduanDuoxuan(question) {
    let answerList = question.regExAnswer;
    let danxuanDaAn = [];
    if (this.data.modeType == 6 || this.data.modeType == 3) {
      question.isFinsh = false;
      for (let j = 0; j < answerList.length; j++) {
        if (question.myAnswer == undefined) {
          danxuanDaAn.push('normal1');
        } else {
          let isExist = false;
          for (let i = 0; i < question.myAnswer.length; i++) {
            if (question.myAnswer[i] == this.data.letter[j]) {
              isExist = true;
            }
          }
          if (isExist) {
            danxuanDaAn.push('select1');
          } else {
            danxuanDaAn.push('normal1');
          }
        }
      }
    } else {
      for (let j = 0; j < answerList.length; j++) {
        if (question.myAnswer == undefined) {
          danxuanDaAn.push('normal1');
        } else {
          if (question.isFinsh) {
            if (question.answer.indexOf(this.data.letter[j]) != -1) {
              danxuanDaAn.push('select1');
            } else {
              let isExist = false;
              for (let i = 0; i < question.myAnswer.length; i++) {
                if (question.myAnswer[i] == this.data.letter[j]) {
                  isExist = true;
                }
              }
              if (isExist) {
                danxuanDaAn.push('error1');
              } else {
                danxuanDaAn.push('normal1');
              }
            }
          } else {
            let isExist = false;
            for (let i = 0; i < question.myAnswer.length; i++) {
              if (question.myAnswer[i] == this.data.letter[j]) {
                isExist = true;
              }
            }
            if (isExist) {
              danxuanDaAn.push('select1');
            } else {
              danxuanDaAn.push('normal1');
            }
          }
        }
      }
    }
    question.isPanduanDuoxuan = danxuanDaAn;
    this.data.questions[this.data.currentTab] = question;
    this.setData({
      questions: this.data.questions,
      currentQuestion: question
    })
  },

  /**
   * 判断题点击事件
   */
  panduan(e) {
    let question = this.data.questions[this.data.currentTab];
    if (question.isFinsh) { return; }
    let answer = e.currentTarget.dataset.obj;
    question.isFinsh = true;
    question.myAnswer = answer;
    //答案正确直接进入下题
    if (this.data.modeType == 6 || this.data.modeType == 3) {
      this.next();
    } else {
      if (question.myAnswer == question.answer) {
        this.next();
      } else {
        this.isPanduanTi(question);
      }
    }
  }

  /**
   * 判断题的时候使用
  */
  , isPanduanTi(question) {
    let obj = ['对', '错'];
    let danxuanDaAn = [];

    if (this.data.modeType == 6 || this.data.modeType == 3) {
      question.isFinsh = false;
      for (let j = 0; j < obj.length; j++) {
        if (question.myAnswer == undefined) {
          danxuanDaAn.push('normal');
        } else {
          if (question.myAnswer == obj[j]) {
            danxuanDaAn.push('select');
          } else {
            danxuanDaAn.push('normal');
          }
        }
      }
    } else {
      for (let j = 0; j < obj.length; j++) {
        if (question.myAnswer == undefined) {
          danxuanDaAn.push('normal');
        } else {
          if (question.answer == obj[j]) {
            danxuanDaAn.push('select');
          } else {
            if (question.myAnswer == obj[j]) {
              danxuanDaAn.push('error');
            } else {
              danxuanDaAn.push('normal');
            }
          }
        }
      }
    }
    question.isPanduanti = danxuanDaAn;
    this.data.questions[this.data.currentTab] = question;
    //需要记录刷新
    this.setData({
      questions: this.data.questions,
      currentQuestion: question
    })
  }

  /**
   * 单选和多选点击
   * 选择答案的时候使用
   */
  , selectAnser(e) {
    let index = e.currentTarget.dataset.index;
    let letter = this.data.letter[index];
    let question = this.data.questions[this.data.currentTab];
    if (question.isFinsh) { return; }
    if (question.type == '单选题') {
      question.isFinsh = true;
      question.myAnswer = letter;
      //答案正确直接进入下题
      if (this.data.modeType == 6 || this.data.modeType == 3) {
        this.next();
      } else {
        if (question.myAnswer == question.answer) {
          this.next();
        } else {
          this.isPanduanDanxuan(question);
        }
      }
    } else {
      if (question.myAnswer != '' && question.myAnswer != undefined) {
        if (question.myAnswer.indexOf(letter) == -1) {
          question.myAnswer = question.myAnswer + letter;
        } else {
          question.myAnswer = question.myAnswer.replace(letter, '');
        }
      } else {
        question.myAnswer = this.data.letter[index];
      }
      question.myAnswer = question.myAnswer.split('').sort().join('');
      this.isPanduanDuoxuan(question);
    }
  }

  /**
   * 点击查看解析
   */
  , lookJiexu() {
    this.lockJixie = true;
    let question = this.data.questions[this.data.currentTab];
    question.isFinsh = true;
    question.myAnswer = question.myAnswer == undefined ? '' : question.myAnswer;
    this.data.questions[this.data.currentTab] = question;
    this.loadQuestionsHtml(this.data.currentTab)
  }
  ,
  /**
   * 保存交卷数据
   */
  jiaojuan() {
    let questions = this.data.questions;
    if (questions != null && questions.length > 0) {
      let questionslist = [];
      for (let i = 0; i < questions.length; i++) {
        let question = questions[i];
        if (!utils.isEmpty(question.myAnswer)) {
          let isCorrect = 0;
          let score = 0;
          if (question.type == '问答题' || question.type == '案例题' || question.type == '填空题') {
            isCorrect = 1;
            score = question.score;
          } else {
            if (question.myAnswer == question.answer) {
              isCorrect = 1;
              score = question.score;
            } else {
              isCorrect = 0;
            }
          }
          questionslist.push({
            id: question.id,
            questionId: question.questionId,
            myAnswer: question.myAnswer,
            answerTime: question.answerTime,
            isCorrect: isCorrect,
            score: score
          })
        }
      }
      let question = questions[this.data.currentTab];
      let json = {
        eid: this.data.testInfo.id,
        currentQuestion: question.questionId,
        currentQuestionOrder: question.orders,
        questions: questionslist
      }
      wcache.put("jiaojuan", json);
    }
  },

  /**
   * 跳转答题卡
   */
  toAnswerSheet() {
    wx.navigateTo({
      url: './answersheet/answersheet?type=' + this.data.modeType,
    })
  },

  timing() {
    isStop = true;
    wx.showModal({
      title: '休息一下',
      content: '已用时' + this.data.clock,
      success: () => {
        isStop = false;
        countdown(this);
      }
    })
  },

  //获取当前需要跳转的界面
  getCurrentPostion() {
    for (let i = 0; i < this.data.questions.length; i++) {
      let question = this.data.questions[i];
      if (this.data.testInfo.currentQuestionOrder == question.orders) {
        return i;
      }
    }
    return 0;
  },

  /**
   * 点击交卷按钮
   */
  submitjisojuan() {
    this.jiaojuan();
    let jisojusn = wcache.get("jiaojuan", null);
    app.httpUtils.postJsonLoading(app.Api.FINISH, JSON.stringify(jisojusn)).then(res => {
      wcache.remove("jiaojuan");
      this.saveTi();
      wx.redirectTo({
        url: '/pages/zuoti/report/report',
      })
    })
  },

  /**
   * 解决错题的使用的接口
   */
  submitError() {
    if (this.data.modeType == 7) {
      let question = this.data.questions[this.data.currentTab];
      if (question.myAnswer == undefined) return
      app.httpUtils.postLoading(app.Api.ANSWERERROR, {
        id: question.id,
        answer: question.myAnswer
      }).then(res => { })
    }
  },

  //收藏
  collectAndCancel() {
    app.httpUtils.postLoading(app.Api.COLLECTION, {
      uid: app.globalData.userBean().id,
      testId: this.data.testInfo.testId == undefined ? this.data.testInfo.id : this.data.testInfo.testId,
      questionId: this.data.questions[this.data.currentTab].questionId
    }).then(res => {
      if (res.code == '00') {
        let question = this.data.questions[this.data.currentTab];
        question.isCollect = res.data;
        this.data.questions[this.data.currentTab] = question;
        this.setData({ questions: this.data.questions })
      }
    })
  },

  //添加笔记
  addnote(){
    let question = this.data.questions[this.data.currentTab];
    wx.navigateTo({
      url: '../we/edtext/edtext?type=2&text='+question.noteContent,
    })
  },

  marknote(note){
    app.httpUtils.postLoading(app.Api.MAKENOTES, {
      uid: app.globalData.userBean().id,
      testId: this.data.testInfo.testId == undefined ? this.data.testInfo.id : this.data.testInfo.testId,
      questionId: this.data.questions[this.data.currentTab].questionId,
      content:note.text
    }).then(res => {
      if (res.code == '00') {
        let question = this.data.questions[this.data.currentTab];
        this.data.questions[this.data.currentTab] = question;
        question.noteContent = note.text
        this.setData({ questions: this.data.questions })
      }
    })
  },

  sumbiterror(){
    let question = this.data.questions[this.data.currentTab];
    wx.navigateTo({
      url: '../errorrecovery/errorrecovery?qid=' + question.questionId,
    })
  }
})